<style lang="less">
    @import '../../../styles/common.less';
    @import './article-publish.less';
</style>

<template>
    <div>
        <Row>
            <Col span="24">
            <Card>
                <Form :label-width="80">
                    <FormItem label="公告标题" :error="articleError">
                        <Input v-model="articleTitle" @on-blur="handleArticletitleBlur" icon="android-list"/>
                    </FormItem>
                </Form>
                <Form :label-width="80">
                    <FormItem label="公告摘要" :error="zhaiyaoError">
                        <Input v-model="articleZhaiyao" @on-blur="zhaiyaoArticletitleBlur" icon="android-list"/>
                    </FormItem>
                </Form>
                <div style="line-height: 58px;">
                    <label class="ivu-form-item-label" style="width:80px;text-align: right;vertical-align: middle;float: left;font-size: 12px;color: #495060;line-height:36px;padding: 10px 12px 10px 0;box-sizing: border-box;">上传封面</label>
                    <div class="demo-upload-list" v-if="titleImg">
                        <img :src="titleImg">
                        <div class="demo-upload-list-cover">
                            <Icon type="ios-eye-outline" @click.native="handleView()"></Icon>
                        </div>

                    </div>
                    <div class="ivu-upload" @click="fengmian" style="display: inline-block; width: 58px;"><div class="ivu-upload ivu-upload-drag"><input type="file" multiple="multiple" class="ivu-upload-input"> <div style="width: 58px; height: 58px; line-height: 58px;"><i class="ivu-icon ivu-icon-camera" style="font-size: 20px;"></i></div></div>  <!----></div>
                </div>
                <div style="line-height: 58px;">
                    <label class="ivu-form-item-label" style="width:80px;text-align: right;vertical-align: middle;float: left;font-size: 12px;color: #495060;line-height:36px;padding: 10px 12px 10px 0;box-sizing: border-box;">上传图片</label>
                    <div class="ivu-upload" @click="files" style="display: inline-block; width: 58px;"><div class="ivu-upload ivu-upload-drag"><input type="file" multiple="multiple" class="ivu-upload-input"> <div style="width: 58px; height: 58px; line-height: 58px;"><i class="ivu-icon ivu-icon-camera" style="font-size: 20px;"></i></div></div>  <!----></div>
                </div>
                <input style="display: none" id="fengmian" type="file"   @change="fengmianChange">

                <input style="display: none" id="filed" type="file"   @change="upFileChange">
                <div class="margin-top-20">
                    <textarea id="articleEditor" v-model="inner"></textarea>
                </div>
            </Card>
            </Col>
        </Row>
        <Col span="24">
        <Card>
            <p slot="title">
                <Icon type="paper-airplane"></Icon>
                发布
                </p>
            <Row class="">
                <span class="publish-button"><Button @click="handlePublish" :loading="publishLoading" icon="ios-checkmark" style="width:90px;" type="primary">发布</Button></span>
                <span class="publish-button"><Button @click="handlePreview">预览</Button></span>
            </Row>
        </Card>
        </Col>
        <Modal title="图片预览" v-model="visible">
            <img :src="imgName " v-if="visible" style="width: 100%">
        </Modal>
    </div>
</template>

<script>
    import tinymce from 'tinymce'
    import $http from '../../../utils/axiosWrap'

    export default {
        name: 'artical-publish',
        data () {
            return {
                visible: false,
                articleTitle: '',
                articleError: '',
                articleZhaiyao: '',
                zhaiyaoError: '',
                showLink: false,
                fixedLink: '',
                articlePath: '',
                articlePathHasEdited: false,
                zhaiyaoPathHasEdited: false,
                publishTime: '',
                publishTimeType: 'immediately',
                editPublishTime: false, // 是否正在编辑发布时间
                classificationList: [],
                offenUsedClass: [],
                publishLoading: false,
                uploadList: [],
                imgName: '',
                titleImg: '',
                changeId: '',
                inner: ''
            };
        },
        created (){
            let innerIndex = JSON.parse(localStorage.getItem('changeInner'))
            this.articleTitle = innerIndex.biaoti
            this.articleZhaiyao = innerIndex.zhaiyao
            this.changeId = innerIndex.id
            if (innerIndex.pic) {
                this.titleImg = innerIndex.pic
            }
            this.inner = innerIndex.neirong
        },
        methods: {
            handleArticletitleBlur () {
                if (this.articleTitle.length !== 0) {
                    if (!this.articlePathHasEdited) {
                        this.articlePathHasEdited = true;
                        this.showLink = true;
                    }
                } else {
                    this.articleError = '公告标题不可为空哦';
                    this.$Message.error('公告标题不可为空哦');
                }
            },
            zhaiyaoArticletitleBlur () {
                if (this.articleZhaiyao.length !== 0) {
                    if (!this.zhaiyaoPathHasEdited) {
                        this.zhaiyaoPathHasEdited = true;
                        this.showLink = true;
                    }
                } else {
                    this.zhaiyaoError = '公告摘要不可为空哦';
                    this.$Message.error('公告摘要不可为空哦');
                }
            },
            handleEditOpenness () {
                this.editOpenness = !this.editOpenness;
            },
            handleSaveOpenness () {
                this.Openness = this.currentOpenness;
                this.editOpenness = false;
            },
            cancelEditOpenness () {
                this.currentOpenness = this.Openness;
                this.editOpenness = false;
            },
            handleEditPublishTime () {
                this.editPublishTime = !this.editPublishTime;
            },
            handleSavePublishTime () {
                this.publishTimeType = 'timing';
                this.editPublishTime = false;
            },
            cancelEditPublishTime () {
                this.publishTimeType = 'immediately';
                this.editPublishTime = false;
            },
            setPublishTime (datetime) {
                this.publishTime = datetime;
            },
            setClassificationInAll (selectedArray) {
                this.classificationFinalSelected = selectedArray.map(item => {
                    return item.title;
                });
            },
            setClassificationInOffen (selectedArray) {
                this.classificationFinalSelected = selectedArray;
            },
            handleAddNewTag () {
                this.addingNewTag = !this.addingNewTag;
            },

            canPublish () {
                if (this.articleTitle.length === 0) {
                    this.$Message.error('请输入公告标题');
                    return false;
                }
                if (this.articleZhaiyao.length === 0) {
                    this.$Message.error('请输入公告摘要');
                    return false;
                }
                if (!this.titleImg) {
                    if (!document.getElementById('fengmian').files[0] ) {
                        this.$Message.error('请选择公告封面');
                        return false;
                    }
                }
                if (!tinymce.activeEditor.getContent()) {
                    this.$Message.error('请输入内容');
                    return false;
                } else {
                    return true;
                }
            },
            handlePreview () {
                if (this.canPublish()) {
                    if (this.publishTimeType === 'immediately') {
                        let date = new Date();
                        let year = date.getFullYear();
                        let month = date.getMonth() + 1;
                        let day = date.getDate();
                        let hour = date.getHours();
                        let minute = date.getMinutes();
                        let second = date.getSeconds();
                        localStorage.publishTime = year + ' 年 ' + month + ' 月 ' + day + ' 日 -- ' + hour + ' : ' + minute + ' : ' + second;
                    } else {
                        localStorage.publishTime = this.publishTime; // 本地存储发布时间
                    }
                    localStorage.articleTitle = this.articleTitle;
                    localStorage.content = tinymce.activeEditor.getContent();
                    this.$router.push({
                        name: 'preview'
                    });
                }
            },
            handleSaveDraft () {
                if (!this.canPublish()) {
                    //
                }
            },
            handlePublish () {
                let _this = this
                if (_this.canPublish()) {
                    let setUrl
                    _this.publishLoading = true;
                    let params = new FormData()
                    params.append('biaoti', _this.articleTitle)
                    params.append('zhaiyao', _this.articleZhaiyao)
                    params.append('fengmian', _this.titleImg)
                    params.append('neirong', tinymce.activeEditor.getContent())
                    if (_this.changeId) {
                        params.append('id', _this.changeId / 1)
                        setUrl = '/gonggao/updateGonggao'
                    } else {
                        setUrl = '/gonggao/addGonggao'
                    }
                    $http.post(setUrl, params, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(function (res) {
                        if (res.suc) {
                            setTimeout(() => {
                                _this.publishLoading = false;
                                _this.$router.push({
                                    name: 'announcement_index'
                                })
                                _this.$Notice.success({
                                    title: '保存成功',
                                    desc: '公告《' + _this.articleTitle + '》保存成功'
                                });
                            }, 1000);
                        } else {
                            _this.publishLoading = false;
                            _this.$Notice.error({
                                title: '保存失败',
                                desc: '公告《' + _this.articleTitle + '》保存失败'
                            });
                        }
                    })
                }
            },
            handleSelectTag () {
                localStorage.tagsList = JSON.stringify(this.articleTagSelected); // 本地存储文章标签列表
            },
            upFileChange () {
                let _this = this
                let params = new FormData()
                params.append('pic', document.getElementById('filed').files[0])
                $http.post('/gonggao/addFile', params, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(function (res) {
                    if (res.suc) {
                        $("<img style='max-width:80%' src=" +res.result + ">").appendTo(document.getElementById('articleEditor_ifr').contentWindow.document.getElementById('tinymce'))
                        _this.$Message.info('图片上传成功!')
                    } else {
                        _this.$Message.error('图片上传失败!')
                    }
                })
            },
            handleView () {
                this.imgName = this.titleImg;
                this.visible = true;
            },
            files () {
                document.getElementById("filed").click()
            },
            fengmian () {
                document.getElementById("fengmian").click()
            },
            fengmianChange () {
                let _this = this
                let params = new FormData()
                params.append('pic', document.getElementById('fengmian').files[0])
                $http.post('/gonggao/addFile', params, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(function (res) {
                    if (res.suc) {
                        console.log(res)
                        _this.titleImg = res.result
                        _this.$Message.info('图片上传成功!')
                    } else {
                        _this.$Message.error('图片上传失败!')
                    }
                })
            }
        },
        computed: {
            completeUrl () {
                let finalUrl = this.fixedLink + this.articlePath;
                localStorage.finalUrl = finalUrl; // 本地存储完整文章路径
                return finalUrl;
            }
        },
        mounted () {
            tinymce.init({
                selector: '#articleEditor',
                branding: false,
                elementpath: false,
                height: 600,
                language: 'zh_CN.GB2312',
                menubar: 'edit insert view format table tools',
                theme: 'modern',
                plugins: [
                    'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                    'searchreplace visualblocks visualchars code fullscreen fullpage',
                    'insertdatetime media nonbreaking save table contextmenu directionality',
                    'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                ],
                toolbar1: ' newnote print fullscreen preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
                autosave_interval: '20s',
                image_advtab: true,
                table_default_styles: {
                    width: '100%',
                    borderCollapse: 'collapse'
                }
            });
        },
        destroyed () {
            tinymce.get('articleEditor').destroy();
        }
    };
</script>
<style>
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
